package cn.tedu.project.oa.dingding;

import cn.tedu.project.oa.attendance.service.AttendanceService;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiAttendanceListRequest;
import com.dingtalk.api.response.OapiAttendanceListResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.dingtalk.open.app.api.GenericEventListener;
import com.dingtalk.open.app.api.OpenDingTalkStreamClientBuilder;
import com.dingtalk.open.app.api.message.GenericOpenDingTalkEvent;
import com.dingtalk.open.app.api.security.AuthClientCredential;
import com.dingtalk.open.app.stream.protocol.event.EventAckStatus;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import shade.com.alibaba.fastjson2.JSONObject;
import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Timer;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;


@RestController
@Slf4j
public class DingDingConsumer {
    @Autowired
    private AttendanceService attendanceService;

    @PostConstruct
    public void monitor() throws Exception {
        OpenDingTalkStreamClientBuilder
                .custom()
                .credential(new AuthClientCredential(DingDingConstant.APP_KEY, DingDingConstant.APP_SECRET))
                //注册事件监听
                .registerAllEventListener(new GenericEventListener() {
                    public EventAckStatus onEvent(GenericOpenDingTalkEvent event) {
                        try {
                            //事件唯一Id
                            String eventId = event.getEventId();
                            //事件类型
                            String eventType = event.getEventType();
                            //事件产生时间
                            Long bornTime = event.getEventBornTime();
                            //获取事件体
                            JSONObject bizData = event.getData();
                            //处理事件
                            saveAttendance(bizData);
                            //消费成功
                            return EventAckStatus.SUCCESS;
                        } catch (Exception e) {
                            //消费失败
                            return EventAckStatus.LATER;
                        }
                    }
                })
                .build().start();
    }

    //监听到打卡事件
    public void saveAttendance(JSONObject bizData){
        log.debug("监听到考勤事件：{}", bizData);
        //将json数据转换为java对象
        ObjectMapper mapper = new ObjectMapper();
        AttendanceEventDTO attendanceEventDTO = null;
        try {
            attendanceEventDTO = mapper.readValue(bizData.toString(), AttendanceEventDTO.class);
        } catch (JsonProcessingException e) {
            //todo 解析失败
            throw new RuntimeException(e);
        }
        AttendanceEventData attendanceEventData = attendanceEventDTO.getDataList().get(0);
//        log.debug("监听到考勤事件：{}", attendanceEventData);
        //获取和用户id
        String userId = attendanceEventData.getUserId();

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 计算当前时间前5秒的时间
        LocalDateTime fiveSecondsBefore = now.minus(5, ChronoUnit.SECONDS);

        // 计算当前时间后5秒的时间
        LocalDateTime fiveSecondsAfter = now.plus(5, ChronoUnit.SECONDS);

        // 格式化日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String WDF = fiveSecondsBefore.format(formatter);
        String WDT = fiveSecondsAfter.format(formatter);



        // 通过调用接口获取考勤打卡结果
        DingTalkClient clientDingTalkClient = new DefaultDingTalkClient(DingDingConstant.GET_ATTENDANCE_URL);
        OapiAttendanceListRequest requestAttendanceListRequest = new OapiAttendanceListRequest();
        // 查询考勤打卡记录的起始时间
        requestAttendanceListRequest.setWorkDateFrom(WDF);
        // 查询考勤打卡记录的结束时间
        requestAttendanceListRequest.setWorkDateTo(WDT);
        // 员工在企业内的userid列表，最多不能超过50个。
        requestAttendanceListRequest.setUserIdList(Arrays.asList(userId));
        // 表示获取考勤数据的起始点
        requestAttendanceListRequest.setOffset(0L);
        // 表示获取考勤数据的条数，最大不能超过50条。
        requestAttendanceListRequest.setLimit(20L);

        //延迟1秒等待钉钉数据同步
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        OapiAttendanceListResponse response = null;
        try {
            response = clientDingTalkClient.execute(requestAttendanceListRequest, DingDingService.access_token);
        } catch (ApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (response != null){
            attendanceService.insertAttendance(response);
        }
    }


}
